package com.example.oj.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.oj.Util.CheckRole;
import com.example.oj.common.Result;
import com.example.oj.entity.User;
import com.example.oj.entity.UserData;
import com.example.oj.service.UserDataService;
import com.example.oj.service.UserService;
import com.example.oj.vo.JwtInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import static com.example.oj.Util.JWTUtil.*;


@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserDataService userDataService;

    @GetMapping
    public Result<?>getUser(@RequestParam(value = "id") Integer id){
        User user = userService.getById(id);
        return Result.success(user);
    }

    @PostMapping("/login")
    public Result<?> login(@RequestBody User user) {
        Integer flag = userService.login(user);
        if(flag == -1) return Result.error("-1", "用户名或密码错误");
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername());
        user = userService.getOne(wrapper);
        UserData userData = userDataService.getById(user.getId());
        userData.setJwt(JWT_Create(user));
        return Result.success(userData);
    }

    @PostMapping("/register")
    public Result<?> register(@RequestBody User user) {
        Integer flag = userService.register(user);
        if(flag != 0) return Result.error("-1", "用户名已存在");
        return Result.success();
    }

    @PostMapping("/checkRole")
    public Result<?> checkRole(@RequestBody UserData userData){
        String jwt = userData.getJwt();
        Result<?> result = CheckRole.check(jwt);
        if(!result.getCode().equals("0")) return result;
        return Result.success();
    }
    @PostMapping("/getJwtInfo")
    public Result<?> getJwtInfo(@RequestBody UserData userData){
        String jwt = userData.getJwt();
        if(!JWT_Check(jwt)) return Result.error("-1", "登录异常");
        JwtInfo jwtInfo = new JwtInfo();
        jwtInfo.setId(JWT_getUserId(jwt));
        jwtInfo.setUsername(JWT_getUsername(jwt));
        jwtInfo.setRole(JWT_getRole(jwt));
        return Result.success(jwtInfo);
    }
}
